import Vue from "vue";
import Vuex from "vuex"; // 引入vuex
import Vant from "vant"; // 引入vant
import "vant/lib/index.css";
import App from "./App.vue";
import router from "./router";
import { serverUrl } from "./utils/request"; //  导入基础路径
import { loadCartsAPI } from "./service/carts";

Vue.use(Vant); // 使用vant
Vue.use(Vuex); // 使用vuex
Vue.config.productionTip = false;

// 全局过滤器
Vue.filter("dalImg", (url) => {
  if (url) {
    if (url.startsWith("http")) {
      return url;
    }
    return serverUrl + url;
  } else {
    return "https://img1.baidu.com/it/u=1985847945,925223576&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=281";
  }
});

const store = new Vuex.Store({
  state: {
    carts: [],
  },
  actions: {
    async loadCarts({ commit }) {
      const res = await loadCartsAPI();
      commit("loadCartsEnd", res.data);
    },
  },
  mutations: {
    loadCartsEnd(state, payload) {
      state.carts = payload.filter((item) => item.product); // 赋值，并过滤存在的商品
    },
    // 重置购物车信息
    resetCarts(state) {
      state.carts = [];
    },
  },
  // 相当于计算属性
  getters: {
    // 购物车中数据的数量
    cartCount(state) {
      return state.carts.length;
    },
  },
});

new Vue({
  router, // 使用路由插件
  store,
  render: (h) => h(App),
}).$mount("#app");
